import { ref, computed, watch } from 'vue'
import { debounce } from 'lodash'
import { createNewBusiness, createNewFeeRecord } from './createBusinessRecords.js'

export function useTableData(props, emit) {



    const shouldCreateNewRecord = ref(false);   //来决定是否创建新的记录

    const localTableData = ref(getInitialTableData(props.tableData))

    const businessType = ref(props.businessType)
    console.log('businessType computed:', businessType);
    const localFeeData =  ref(
        Array.isArray(props.feeData) && props.feeData.length > 0
            ? props.feeData.map(row => ({
                ...row,
                parentId: row.parentId || (localTableData.value[0] && localTableData.value[0].id)
            }))
            : [createNewFeeRecord(localTableData.value[0] && localTableData.value[0].id)]
    );
    const selectedMainRowIndex = ref(0)
    const lastRowUsed = ref(false)
    const activeCell = ref({ row: null, header: null })



    const pendingNewRow = ref(null);
    const showPendingRow = ref(false);


    const visibleTableData = computed(() => {
        console.log('visibleTableData computed:', localTableData.value);
        return localTableData.value;
    });

    const createPendingRow = () => {
        if (!pendingNewRow.value) {
            pendingNewRow.value = createNewRow(localTableData.value.length);
            console.log('Created new pending row:', pendingNewRow.value);
        }
    };

    const filteredFeeData = computed(() => {

        console.log('filteredFeeData', localTableData.value[selectedMainRowIndex.value]);
        const currentMainRowId = localTableData.value[selectedMainRowIndex.value]?.id

        return currentMainRowId && Array.isArray(localFeeData.value)
            ? localFeeData.value.filter(feeRow => feeRow.parentId === currentMainRowId)
            : []
    })

    const canAddNewRow = computed(() => {
        return localTableData.value.length === 0 || lastRowUsed.value
    })

    const debouncedEmit = debounce((data) => {
        console.log('debouncedEmit called, emitting data:', JSON.parse(JSON.stringify(data)));
        emit('update:tableData', JSON.parse(JSON.stringify(data)));
    }, 300, { leading: false, trailing: true });

    const handleCellUpdate = (rowIndex, field, value) => {

        console.log('更新开始:', rowIndex, field, value, typeof value)


        let actualValue = value;
        if (value instanceof Event && value.target && 'value' in value.target) {
            actualValue = value.target.value;
        }
        console.log('handleCellUpdatelocalTableData',localTableData)
        const header = props.headers.find(h => h.field === field);
        const updatedRow = { ...localTableData.value[rowIndex] };
        console.log('updatedRow[field]:', updatedRow[field]);
        console.log('localTableData.value[rowIndex][field]', localTableData.value);
        if (header?.cellType === 'advancedCellTextButton' && header.searchObj) {
            // 处理 advancedCellTextButton 的逻辑
            try {
                const jsonValue = JSON.parse(actualValue);
                const destFields = header.searchObj.destField.split(';');
                destFields.forEach((destField) => {
                    if (Array.isArray(jsonValue)) {
                        const fieldValue = jsonValue.map(item => item[destField]).filter(Boolean).join(', ');
                        updatedRow[destField] = fieldValue;
                    } else if (typeof jsonValue === 'object' && jsonValue !== null) {
                        updatedRow[destField] = jsonValue[destField] || '';
                    }
                });
            } catch (e) {
                console.error('解析 JSON 失败:', e, actualValue);
                updatedRow[field] = actualValue;
            }
        } else {
            if (field in updatedRow) {
                updatedRow[field] = actualValue;
            }
        }

        // 检查是否有实际的更改
        /// const hasChanges = updatedRow[field] !== localTableData.value[rowIndex][field];



        localTableData.value = localTableData.value.map((row, index) => {
            if (index === rowIndex) {
                return { ...row, [field]: actualValue };
            }
            return row;
        });
        console.log('更新后的rowIndex:', rowIndex);
        console.log('更新后的localTableDatalength:', localTableData.value.length);
        console.log('localTableData.value[rowIndex]', localTableData.value[rowIndex]);

        console.log('rowIndex=== localTableData.value.length', rowIndex === localTableData.value.length - 1);
        console.log('!isRowEmpty', !isRowEmpty(localTableData.value[rowIndex]));

        if (rowIndex === localTableData.value.length - 1 && !isRowEmpty(localTableData.value[rowIndex])) {
            console.log('createPendingRow', rowIndex === localTableData.value.length - 1);
            // showPendingRow.value = true;
            // createPendingRow();
            const hasEmptyIdRow = localTableData.value.some(row => row.id === '');

            if (!hasEmptyIdRow) {
                const newRow = createNewBusiness("",businessType)
                localTableData.value.push(newRow)
                console.log('Created new record for row:', localTableData)
            } else {
                console.log('Skipped creating new row: Empty id row already exists')
            }
        }

        console.log('更新后的localTableData:', JSON.parse(JSON.stringify(localTableData.value)));
        emit('update:tableData', localTableData.value[rowIndex]);

    }

    const handleCellInput = (rowIndex, field, value) => {
        console.log('输入:', rowIndex, field, value)

        const header = props.headers.find(h => h.field === field)
        if (header?.cellType === 'advancedCellTextButton') {
            return
        }

        let actualValue = value
        if (value instanceof Event && value.target && 'value' in value.target) {
            actualValue = value.target.value
        }

        if (props.headers.find(h => h.field === field)?.cellType === 'cellDate') {
            localTableData.value[rowIndex][field] = actualValue
        } else if (typeof actualValue === 'string' && actualValue.startsWith('{') && actualValue.endsWith('}')) {
            try {
                const jsonValue = JSON.parse(actualValue)
                Object.keys(jsonValue).forEach(key => {
                    if (key in localTableData.value[rowIndex]) {
                        localTableData.value[rowIndex][key] = jsonValue[key]
                    }
                })
            } catch (e) {
                console.error('解析 JSON 失败:', e)
                localTableData.value[rowIndex][field] = actualValue
            }
        } else {
            localTableData.value[rowIndex][field] = actualValue
        }

        ///  checkRowCompletion(rowIndex)


        // debouncedEmit(localTableData.value[rowIndex])

        console.log('立即更新后的数据:', JSON.parse(JSON.stringify(localTableData.value[rowIndex])))
    }


    const handleRowFocus = (row, index) => {

        console.log('ShandleRowFocus', index)
        if (selectedMainRowIndex.value === index) {
            return
        }

        selectedMainRowIndex.value = index
        console.log('Selected main row index:', index)
        console.log('Selected main row ID:', row.id)


        console.log('生成新的前 id:', localTableData.value)
        console.log('生成新的前 id:', localTableData.value[index].id )
        if (localTableData.value[index].id === '') {
            localTableData.value[index].id = `new-${props.businessType}-${Date.now()}`
            console.log('生成新的 id:', localTableData.value[index].id)
        }
        console.log('生成新的后 id:', localTableData.value[index].id )
        //  emit('rowFocus', JSON.parse(JSON.stringify(row)))
        // 同步 feeTable 数据到 localFeeData
        if (localTableData.value[index].feeTable) {
            localFeeData.value = localTableData.value[index].feeTable.map(feeRow => ({
                ...feeRow,
                parentId: localTableData.value[index].id
            }));
        } else {
            localFeeData.value = [createNewFeeRecord(localTableData.value[index].id)];
        }

    }

    const addNewRow = () => {
        if (pendingNewRow.value) {
            localTableData.value.push(pendingNewRow.value);
            pendingNewRow.value = null;
            showPendingRow.value = false;
        }

    }

    const handleFeeCellUpdate = debounce((rowIndex, field, value) => {
        console.log('Fee更新开始:', rowIndex, field, value, typeof value)

        let actualValue = value
        if (value instanceof Event && value.target && 'value' in value.target) {
            actualValue = value.target.value
        }

        const header = props.feeHeaders.find(h => h.field === field)

        const localIndex = localFeeData.value.findIndex(row => row.id === filteredFeeData.value[rowIndex].id)

        if (localIndex !== -1) {
            if (header?.cellType === 'advancedCellTextButton' && header.searchObj) {
                try {
                    const jsonValue = JSON.parse(actualValue)
                    console.log('解析后的 JSON 值:', jsonValue)

                    const destFields = header.searchObj.destField.split(';')
                    console.log('目标字段:', destFields)

                    destFields.forEach((destField, index) => {
                        console.log(`处理字段 ${destField} (index: ${index})`)
                        if (Array.isArray(jsonValue)) {
                            const fieldValue = jsonValue.map(item => item[destField]).filter(Boolean).join(', ')
                            console.log(`数组情况 - ${destField}:`, fieldValue)
                            localFeeData.value[localIndex][destField] = fieldValue
                        } else if (typeof jsonValue === 'object' && jsonValue !== null) {
                            console.log(`对象情况 - ${destField}:`, jsonValue[destField])
                            localFeeData.value[localIndex][destField] = jsonValue[destField] || ''
                        }
                    })
                } catch (e) {
                    console.error('解析 JSON 失败:', e, actualValue)
                    localFeeData.value[localIndex][field] = actualValue
                }
            } else {
                localFeeData.value[localIndex][field] = actualValue
            }

            const parentId = localFeeData.value[localIndex].parentId
            const parentIndex = localTableData.value.findIndex(row => row.id === parentId)

            if (parentIndex !== -1) {
                if (!localTableData.value[parentIndex].feeTable) {
                    localTableData.value[parentIndex].feeTable = []
                }

                const feeIndex = localTableData.value[parentIndex].feeTable.findIndex(fee => fee.id === localFeeData.value[localIndex].id)
                if (feeIndex !== -1) {
                    localTableData.value[parentIndex].feeTable[feeIndex] = { ...localFeeData.value[localIndex] }
                } else {
                    localTableData.value[parentIndex].feeTable.push({ ...localFeeData.value[localIndex] })
                }

                if (!isRowEmpty(localFeeData.value[localIndex])) {
                    addNewFeeRow(parentId)
                }

                debouncedEmit(JSON.parse(JSON.stringify(localTableData.value[parentIndex])))
            } else {
                console.error('无法找到对应的主表记录')
            }

            console.log('Fee更新后:', localIndex, field, localFeeData.value[localIndex])
            checkFeeRowCompletion(localIndex)
        } else {
            console.error('无法找到对应的费用行')
        }
    }, 300)

    const handleFeeCellInput = (rowIndex, field, value) => {
        console.log('Fee输入:', rowIndex, field, value)

        let actualValue = value
        if (value instanceof Event && value.target && 'value' in value.target) {
            actualValue = value.target.value
        }

        const localIndex = localFeeData.value.findIndex(row => row.id === filteredFeeData.value[rowIndex].id)

        if (localIndex !== -1) {
            localFeeData.value[localIndex][field] = actualValue

            const parentId = localFeeData.value[localIndex].parentId
            const parentIndex = localTableData.value.findIndex(row => row.id === parentId)

            if (parentIndex !== -1) {
                if (!localTableData.value[parentIndex].feeTable) {
                    localTableData.value[parentIndex].feeTable = []
                }

                const feeIndex = localTableData.value[parentIndex].feeTable.findIndex(fee => fee.id === localFeeData.value[localIndex].id)
                if (feeIndex !== -1) {
                    localTableData.value[parentIndex].feeTable[feeIndex] = { ...localFeeData.value[localIndex] }
                } else {
                    localTableData.value[parentIndex].feeTable.push({ ...localFeeData.value[localIndex] })
                }

                emit('update:tableData', localTableData.value[parentIndex])
            } else {
                console.error('无法找到对应的主表记录')
            }

            checkFeeRowCompletion(localIndex)
        } else {
            console.error('无法找到对应的费用行')
        }
    }

    const handleFeeCellFocus = (rowIndex, field) => {
        activeCell.value = { row: rowIndex, field: field, type: 'fee' }
    }

    const handleCellBlur = () => {
        activeCell.value = { row: null, header: null }
    }

    const handleTableClick = (event) => {
        if (event.target.tagName !== 'INPUT' && canAddNewRow.value) {
            addNewRow()
        }
    }

    const handleFeeTableClick = (event) => {
        if (event.target.tagName !== 'INPUT' && filteredFeeData.value.every(row => !isRowEmpty(row))) {
            addNewFeeRow(localTableData.value[selectedMainRowIndex.value].id)
        }
    }

    const onCalculatorSelected = (calculator) => {
        console.log('Calculator selected:', calculator)
        emit('calculatorSelected', calculator)
    }

    const onUnitPriceChange = (unitPrice) => {
        console.log('Unit price changed:', unitPrice)
        emit('unitPriceChange', unitPrice)
    }

    const onAgentRateChange = (agentRate) => {
        console.log('Agent rate changed:', agentRate)
        emit('agentRateChange', agentRate)
    }

    const checkRowCompletion = (rowIndex) => {
        console.log('检查行完成度:', rowIndex, localTableData.value[rowIndex])
        if (rowIndex === localTableData.value.length - 1) {
            lastRowUsed.value = props.headers.some(header =>
                localTableData.value[rowIndex][header.field] &&
                localTableData.value[rowIndex][header.field].toString().trim() !== ''
            )
            if (lastRowUsed.value) {
                addNewRow()
            }
        }
    }

    const checkFeeRowCompletion = (rowIndex) => {
        const currentMainRowId = localTableData.value[selectedMainRowIndex.value]?.id
        const feeRecords = localFeeData.value.filter(feeRow => feeRow.parentId === currentMainRowId)

        if (rowIndex === feeRecords.length - 1) {
            const lastRow = feeRecords[rowIndex]
            if (!isRowEmpty(lastRow)) {
                addNewFeeRow(currentMainRowId)
            }
        }
    }

    const isRowEmpty = (row) => {
        const fieldsToIgnore = ['id', 'parentId']
        return Object.entries(row).every(([key, value]) => {
            if (fieldsToIgnore.includes(key)) {
                return true
            }
            return value === '' || value === null || value === undefined ||
                (typeof value === 'object' && Object.keys(value).length === 0)
        })
    }

    const addNewFeeRow = (parentId) => {
        const feeRecords = localFeeData.value.filter(feeRow => feeRow.parentId === parentId)
        const hasEmptyRow = feeRecords.some(isRowEmpty)

        if (!hasEmptyRow) {
            const newRow = createNewFeeRecord(parentId)
            localFeeData.value.push(newRow)
            console.log('Created new fee record for row:', parentId)

            const parentIndex = localTableData.value.findIndex(row => row.id === parentId)
            if (parentIndex !== -1) {
                if (!localTableData.value[parentIndex].feeTable) {
                    localTableData.value[parentIndex].feeTable = []
                }
                localTableData.value[parentIndex].feeTable.push(newRow)
            }
        } else {
            console.log('Empty fee record already exists, not adding a new one')
        }
    }

    const createNewRow = (index) => {
        const newRow = {
            id: `row-${index + 1}`,
            businessType: props.businessType,
        }
        props.headers.forEach(header => {
            if (header.field !== 'id') {
                newRow[header.field] = ''
            }
        })
        return newRow
    }


    const createNewRecordIfNeeded = () => {
        if (shouldCreateNewRecord.value && localTableData.value.length > 0) {
            const lastRecord = localTableData.value[localTableData.value.length - 1];

            // 检查最后一条记录是否已被修改
            if (!isRowEmpty(lastRecord)) {
                const newRow = createNewRow(localTableData.value.length);

                // 添加新记录，而不是替换现有记录
                localTableData.value.push(newRow);

                shouldCreateNewRecord.value = false;

                // 发送整个更新后的数据数组，而不仅仅是新行
                emit('update:tableData', JSON.parse(JSON.stringify(localTableData.value)));

                console.log('New record added:', newRow);
            }
        }
    }


    watch(() => props.tableData, (newValue) => {
        console.log('props.tableData:', newValue);

        if (JSON.stringify(newValue) !== JSON.stringify(localTableData.value)) {
            localTableData.value = getInitialTableData(newValue)
        }

    }, { deep: true })
    watch(() => props.feeData, (newValue) => {
        localFeeData.value = newValue.map(row => ({...row}))
    }, { deep: true })

    return {
        businessType ,
        localTableData,
        localFeeData,
        selectedMainRowIndex,
        filteredFeeData,
        canAddNewRow,
        handleCellUpdate,
        handleCellInput,
        handleRowFocus,
        addNewRow,
        handleFeeCellUpdate,
        handleFeeCellInput,
        handleFeeCellFocus,
        handleFeeTableClick,
        handleTableClick,
        handleCellBlur,
        onCalculatorSelected,
        onUnitPriceChange,
        onAgentRateChange,
        debouncedEmit,
        activeCell,
        lastRowUsed,
        addNewFeeRow,
        checkRowCompletion,
        checkFeeRowCompletion,
        shouldCreateNewRecord,
        createNewRecordIfNeeded,

        visibleTableData,
        createPendingRow,

        showPendingRow,
        pendingNewRow,
        isRowEmpty
    }
}

function getInitialTableData(data) {
    if (Array.isArray(data)) {
        return data.map(row => ({...row}))
    } else if (typeof data === 'object' && data !== null) {
        return [{ ...data }]
    } else {
        return []
    }
}
